<?php
namespace app\admin\controller;
use app\lib\exception\LoginException;
use app\lib\exception\SuccessMessage;
use app\lib\validate\UserLogin;
use think\Controller;
use think\Request;

use app\admin\model\Admin;

class Login extends Controller
{
    public function index() {
        //如果已经登录
        if(session('admin_id')) {
            $this->redirect('/admin');
        }

        return view();
    }
    //登录
    public function login() {
        (new UserLogin())->goCheck();

        $data = Request::instance()->post();
        $userInfo = Admin::where(array('name' => $data['name']))->find();

        if (empty($userInfo)) {
            throw new LoginException([
                'msg' => '该账户不存在，请先注册'
            ]);
        }
        if ($userInfo['password'] != MD5($data['password'])) {
            throw new LoginException([
                'msg' => '密码不正确'
            ]);
        }
        session('admin_name', $userInfo['name']);
        //更新用户数据
        $this->updateUserLogin($userInfo['id']);
        throw new SuccessMessage([
            'msg' => '登录成功'
        ]);
    }

    //退出
    public function logOut() {
        session('admin_id', null);
        session('admin_name', null);
        $this->redirect('Login/index');
    }

    //更新用户登录信息
    private function updateUserLogin($id) {
        //保存用户信息和登录凭证
        session('admin_id', $id);
        $userData = Admin::where(array('id' => $id))->find();
        $data = array();
        if ($userData) {
            $data['last_login_time'] = date("Y-m-d H:i:s");
            return Admin::where(array('id' => $id))->update($data);
        } else {
            return false;
        }
    }
}